#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include"server.h"
const char* program_name;

// if nonzero, print verbose message
int verbose;

void* xmalloc(size_t size){
    void* ret = malloc(size);
    if(!ret) abort();
    return ret;
}

void* xrealloc(void* ptr,size_t size){
    ptr = realloc(ptr,size);
    if(!ptr) abort();
    return ptr;
}

char* xstrdup(const char* s){
    char* copy = strdup(s);
    if(!copy) abort();
    return copy;
}

void system_error(const char* operation){
    error(operation,strerror(errno));
}

void error(const char* cause,const char* msg){
    fprintf(stderr,"%s: error: (%s) %s\n", program_name, cause, msg);
    exit(1);
}

char * get_self_executable_directory(){
    char link_target[1024];
    int rval = readlink("/proc/self/exe",link_target,sizeof(link_target));
    if(rval == -1) abort();
    link_target[rval] = '\0';
    
    char* last_slash = strrchr(link_target,'/');
    if(!last_slash || last_slash == link_target)
        abort();
    int len = last_slash - link_target;
    char* result = xmalloc(len + 1);
    strncpy(result,link_target,len);
    result[len] = 0;
    return result;
}
